//
//  DeviceMusicVc.m
//  ainkjj
//
//  Created by zhiyiLiu on 2020/3/12.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "DeviceMusicVc.h"
#import "DeviceVc.h"
#import "GetMusic.h"

@interface DeviceMusicVc ()
@property (nonatomic, assign) NSTimeInterval custom_acceptEventTime;
@property (nonatomic, assign) NSTimeInterval custom_acceptEventInterval;

@end

@implementation DeviceMusicVc
- (IBAction)sliderAction:(UISlider *)sender {
    NSArray *dataArr = nil;
    
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if(!vc.handshake_yes) return;
    
    dataArr =@[ @{@"reg": @"volume", @"value" : @(sender.value)}];
    [vc queryWith_cmd:@"audio" data:dataArr];
}
- (IBAction)play_model_action:(UIButton *)sender {
    
    
    NSArray *dataArr = nil;
    
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if(!vc.handshake_yes) return;
    
    
    NSString *value = vc.audio_play_model;
    
    if ([value isEqualToString:@"single_cycle"]) {
        value = @"random";
        [sender setImage:[UIImage imageNamed:value] forState:UIControlStateNormal];
        
    }else if ([value isEqualToString:@"lists_cycle"]) {
        value = @"single_cycle";
        [sender setImage:[UIImage imageNamed:value] forState:UIControlStateNormal];
    }else if ([value isEqualToString:@"random"]) {
        value = @"lists_cycle";
        [sender setImage:[UIImage imageNamed:value] forState:UIControlStateNormal];
    }else if ([value isEqualToString:@"single"]) {
        
    }
    dataArr =@[ @{@"reg": @"mode", @"value" : value}];
    vc.audio_play_model = value;
    [vc queryWith_cmd:@"audio" data:dataArr];
    
    
}
- (IBAction)play_last_song_action:(UIButton *)sender {
    // 值得提醒一下：如果这里设置了统一的时间间隔，会影响UISwitch,如果想统一设置，又不想影响UISwitch，建议将UIControl分类，改成UIButton分类，实现方法是一样的
    if (self.custom_acceptEventInterval <= 0) {
        // 如果没有自定义时间间隔，则默认为2秒
        self.custom_acceptEventInterval = 1;
    }
    // 是否小于设定的时间间隔
    BOOL needSendAction = (NSDate.date.timeIntervalSince1970 - self.custom_acceptEventTime >= self.custom_acceptEventInterval);
    // 更新上一次点击时间戳
    if (self.custom_acceptEventInterval > 0) {
        self.custom_acceptEventTime = NSDate.date.timeIntervalSince1970;
    }
    
    
    // 两次点击的时间间隔小于设定的时间间隔时，才执行响应事件
    if (needSendAction) {
        DeviceVc *vc = (DeviceVc *)self.parentViewController;
           if(!vc.handshake_yes) return;
           
           GetMusicList *song = nil;
           
           NSString *value = vc.audio_play_model;
           if ([value isEqualToString:@"single_cycle"]) {
               song = vc.currentSong;
               
           }else if ([value isEqualToString:@"lists_cycle"]) {
               NSUInteger index = [vc.currentListData.list indexOfObject:vc.currentSong];
               if (--index == -1) {
                   index = vc.currentListData.list.count - 1;
               }
               if (vc.currentListData.list.count <= index) {
                   return;
               }
               song = [vc.currentListData.list objectAtIndex:index];
               
           }else if ([value isEqualToString:@"random"]) {
               NSUInteger index = arc4random()%vc.currentListData.list.count;
               song = [vc.currentListData.list objectAtIndex:index];
           }
           [self open_song:song];
    }
    
   
    
    
}
- (void)open_song:(GetMusicList *)song{
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if(!vc.handshake_yes) return;
    
    if (![Anktool strIsBlank:song.file_name]) {
        
        NSMutableArray *dataArr = [NSMutableArray array];
        [dataArr addObject:@{
            @"reg" : @"url" // 当前播放的 音频文件路径/URL地址
            , @"value" : song.url
        }];
        [dataArr addObject:@{
            @"reg" : @"status"
            , @"value" : @"open"
        }];
        
        
        [vc queryWith_cmd:@"audio" data:dataArr];
        vc.audio_execute_status = @"open";
        self.play_pause_btn.selected = YES;
        
    }
}
- (IBAction)light_switch_action:(UISwitch *)sender {
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if(!vc.handshake_yes) return;
    

    NSArray *default_reg_dataArr = @[
        @{
            @"reg" : @"lights_sw"//  音量
            ,@"value" : sender.isOn == YES ? @"open" : @"close"
        }
    ];
    [vc queryWith_cmd:@"dev" data:default_reg_dataArr];
   
    
    if (sender.isOn) {
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:app_code forKey:@"appCode"];
        [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
        [dict setObject:vc.deviceInfo.data.device_id forKey:@"deviceId"];
        
        [PPHTTPRequest req:@"java/app/device/openNightLight" parameters:dict success:^(id response) {
            NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
            if ([error_code isEqualToString:@"0"]) {
            }
            else{
                [QMUITips showError:response[@"error_msg"] ];
            }
        } failure:^(NSError *error) {
            [QMUITips showError:[error localizedDescription]];
        }];
    }
    
}
- (IBAction)play_pause_action:(UIButton *)sender {
    
    
    
    NSArray *dataArr = nil;
    //    NSArray *dataArr = @[@{
    //                             @"reg": @"device_get"   //     -------------->设备所有信息 获取
    //                             }
    //                         ];
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if(!vc.handshake_yes) return;
    
    if ([vc.audio_execute_status isEqualToString:@"open"]) {
        // 当前是在播放音乐的状态，再点击一下是暂停
        dataArr =@[ @{@"reg": @"status", @"value" : @"pause"}];
        
        vc.audio_execute_status = @"pause";
        [self jiancha_shifou_hongshui_zanting];
        sender.selected = YES;
    }else if ([vc.audio_execute_status isEqualToString:@"close"]) {
        
        // 当前是没有在播放音乐的状态，再点击一下是播放第一首歌曲
        dataArr =@[ @{@"reg": @"status", @"value" : @"open"}];
        vc.audio_execute_status = @"open";
        sender.selected = NO;
    }else if ([vc.audio_execute_status isEqualToString:@"pause"]) {
        // 当前是在播放音乐的，只是音乐处于暂停状态，再点击一下是恢复
        dataArr =@[ @{@"reg": @"status", @"value" : @"recover"}];
        vc.audio_execute_status = @"recover";
        sender.selected = YES;
    }else if ([vc.audio_execute_status isEqualToString:@"recover"]) {
        // 当前是音乐恢复播放的状态，再点击一下是暂停
        dataArr =@[ @{@"reg": @"status", @"value" : @"pause"}];
        vc.audio_execute_status = @"pause";
        sender.selected = NO;
        [self jiancha_shifou_hongshui_zanting];
    }
    [vc queryWith_cmd:@"audio" data:dataArr];
}
- (void)jiancha_shifou_hongshui_zanting{
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    for (MusicCategoryData *ac in vc.musicCategory.data) {
        DLog(@"%ld----%ld---%@", ac.ID, vc.currentSong.category_id, ac.name)
        if (ac.ID == vc.currentSong.category_id && [ac.name isEqualToString:@"哄睡"]) {
            
            // 哄睡暂停，汇报
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:app_code forKey:@"appCode"];
            [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
            [dict setObject:[Anktool strBlankHolder:vc.entity.device_id] forKey:@"deviceId"];
            
    
            [PPHTTPRequest req:@"java/app/device/closeSleepMusic" parameters:dict success:^(id response) {
                NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
                if ([error_code isEqualToString:@"0"]) {
                   
                }
                else{
                    
                   
                }
                
            } failure:^(NSError *error) {
                
            }];
            
        }
    }
    
    
}
- (IBAction)play_next_song_action:(UIButton *)sender {
    
        // 暴力点击 值得提醒一下：如果这里设置了统一的时间间隔，会影响UISwitch,如果想统一设置，又不想影响UISwitch，建议将UIControl分类，改成UIButton分类，实现方法是一样的
    if (self.custom_acceptEventInterval <= 0) {
        // 如果没有自定义时间间隔，则默认为2秒
        self.custom_acceptEventInterval = 1;
    }
    // 是否小于设定的时间间隔
    BOOL needSendAction = (NSDate.date.timeIntervalSince1970 - self.custom_acceptEventTime >= self.custom_acceptEventInterval);
    // 更新上一次点击时间戳
    if (self.custom_acceptEventInterval > 0) {
        self.custom_acceptEventTime = NSDate.date.timeIntervalSince1970;
    }
    // 两次点击的时间间隔小于设定的时间间隔时，才执行响应事件
    if (needSendAction) {
        // 发送url指令，再发送open指令
        DeviceVc *vc = (DeviceVc *)self.parentViewController;
        if(!vc.handshake_yes) return;
        GetMusicList *song = nil;
        
        NSString *value = vc.audio_play_model;
        if ([value isEqualToString:@"single_cycle"]) {
            song = vc.currentSong;
            
        }else if ([value isEqualToString:@"lists_cycle"]) {
            NSUInteger index = [vc.currentListData.list indexOfObject:vc.currentSong];
            for (NSInteger i = 0; i < vc.currentListData.list.count; i++) {
                GetMusicList *am = vc.currentListData.list[i];
                if ([am.url isEqualToString:vc.currentSong.url]) {
                    index = i;
                    break;
                }
            }
            if (++index == vc.currentListData.list.count) {
                index = 0;
            }
            if (vc.currentListData.list.count <= index) {
                return;
            }
            song = [vc.currentListData.list objectAtIndex:index];
            
        }else if ([value isEqualToString:@"random"]) {
            NSUInteger index = arc4random()%vc.currentListData.list.count;
            song = [vc.currentListData.list objectAtIndex:index];
        }
        
        
        [self open_song:song];
           
        
    }
    
    
    
}
- (IBAction)play_list_aciton:(UIButton *)sender {
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if(!vc.handshake_yes) return;
    
    [vc show_musiclist];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = UIColor.groupTableViewBackgroundColor;
    self.volume_slider.continuous = NO;
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if (vc.entity.is_virtual == NO) {
        self.volume_slider.userInteractionEnabled = NO;
        self.play_list_btn.userInteractionEnabled = NO;
        self.play_mode_btn.userInteractionEnabled = NO;
        self.play_last_song_btn.userInteractionEnabled = NO;
        self.play_next_song_btn.userInteractionEnabled = NO;
        self.play_pause_btn.userInteractionEnabled = NO;
    }
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
